<?php

namespace app\common\service;

class MongoService extends BaseService
{
    // +----------------------------------------------------------------------
    // | （四）字段的计算-循环泵
    // +----------------------------------------------------------------------
    /**
     * 获取循环泵的数据
     * @author hongwei
     * @param $facilityId
     * @param $planNumber
     * @param $field
     * @param $value
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getSulfurPumpNumber($facilityId, $planNumber, $field, $value)
    {
        $control  = new ControlService();
        $startDay = $control->getBeforeStartTime($planNumber);
        $endDay   = $control->getBeforeEndTime($planNumber);
        $result   = $this->getSulfurFieldOfCount($startDay, $endDay, $facilityId, $field, $value);
        return $result;
    }

    // +----------------------------------------------------------------------
    // | （三）字段的计算-供浆量
    // +----------------------------------------------------------------------
    /**
     * 查询供浆量的总和
     * 单位是：立方米/小时
     * @param $facilityId
     * @param $planNumber
     * @return array|float|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getBeforeSulfurSlurrySupplyFieldOfSum($facilityId, $planNumber)
    {
        //参数
        $field    = '$pulp_supply';
        $control  = new ControlService();
        $startDay = $control->getBeforeStartTime($planNumber);
        $endDay   = $control->getBeforeEndTime($planNumber);
        //得到值
        $data = $this->getSulfurFieldOfSumOfFacility($startDay, $endDay, $facilityId, $field);
        //填数
        $data = $data * $this->kBeforeValueFacility($facilityId);
        return $data;
    }

    /**
     * 查询供浆量的小时均值
     * 单位是：立方米/小时
     * @param $facilityId
     * @return float|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getBeforeSulfurSlurrySupplyFieldOfHourAvg($facilityId, $planNumber)
    {
        $data = $this->getBeforeSulfurSlurrySupplyFieldOfSum($facilityId, $planNumber);
        //减排前求和求平均公式
        $formula = new FormulaService();
        $result  = $formula->beforeSumAndAvg($data, 'hour');
        return $result;
    }

    // +----------------------------------------------------------------------
    // | （一）时间的计算
    // +----------------------------------------------------------------------
    /**
     * 全部分钟数
     * @param $startDay
     * @param $endDay
     * @return float
     * @author hongwei 2019-07-22
     */
    public function wholeMinutes($startDay, $endDay)
    {
        if (strpos($startDay, ' ') == false) {
            $startDay = $startDay . ' 00:00:00';
        }
        if (strpos($endDay, ' ') == false) {
            $endDay = $endDay . ' 23:59:59';
        }

        $startStr     = strtotime($startDay);
        $endStr       = strtotime($endDay);
        $wholeMinutes = $endStr - $startStr + 1;  //全部分钟数
        $wholeMinutes = $wholeMinutes / 60;
        return round($wholeMinutes, 0);
    }

    /**
     * 减排前工作的有效条数
     * @return bool|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-23
     */
    public function beforeWorkingMinutes()
    {
        $beforeDayData = $this->getBeforeTime();
        $startDay      = $beforeDayData['start_day'];
        $endDay        = $beforeDayData['end_day'];
        $data          = $this->workingMinutes($startDay, $endDay);
        return (int)$data;
    }

    /**
     * 工作分钟数（这里以脱硫为计算）
     * @param $startDay
     * @param $endDay
     * @param $facilityId
     * @return bool|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function workingMinutesFacility($startDay, $endDay, $facilityId)
    {
        //选择表
        $table = 'company_industry_monitor_sulfur_minute';
        //step2:工作的小时
        $sqlWorkingHoursSql     = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => [
                        'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,],
                        'facility_id' => (int)$facilityId,
                        'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
                        'emissions' => ['$ne' => -1],  //排放量不为-1
                    ]
                ],
                [
                    '$group' => [
                        '_id' => null,
                        'count' => ['$sum' => 1],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandWorkingHoursObj = new \MongoDB\Driver\Command($sqlWorkingHoursSql);
        $workingObj             = $this->mongodb->executeCommand('huanxin', $commandWorkingHoursObj);
        $workingMinutes         = mongoObjToArray($workingObj);
        $workingMinutes         = round($workingMinutes[0]['count']); //四舍五入，因为脱硫有2个设施

        return (int)$workingMinutes;
    }

    /**
     * 工作分钟数（这里以脱硫为计算）
     * @param $startDay
     * @param $endDay
     * @return bool|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function workingMinutes($startDay, $endDay)
    {
        //选择表
        $table = 'company_industry_monitor_sulfur_minute';
        //step2:工作的小时
        $sqlWorkingHoursSql     = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => [
                        'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,],
                        'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
                        'emissions' => ['$ne' => -1],  //排放量不为-1
                    ]
                ],
                [
                    '$group' => [
                        '_id' => null,
                        'count' => ['$sum' => 1],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandWorkingHoursObj = new \MongoDB\Driver\Command($sqlWorkingHoursSql);
        $workingObj             = $this->mongodb->executeCommand('huanxin', $commandWorkingHoursObj);
        $workingMinutes         = mongoObjToArray($workingObj);
        $workingMinutes         = round($workingMinutes[0]['count'] / 2); //四舍五入，因为脱硫有2个设施

        return (int)$workingMinutes;
    }

    /**
     * 丢失分钟数
     * @param string $startDay 开始时间
     * @param string $endDay 结束时间
     * @return bool|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function lostMinutes($startDay, $endDay)
    {
        $wholeMinutes   = $this->wholeMinutes($startDay, $endDay);
        $workingMinutes = $this->workingMinutes($startDay, $endDay);
        $lostMinutes    = (int)$wholeMinutes - (int)$workingMinutes; //丢失小时数
        if ($lostMinutes <= 0) {
            return false;
        }
        return $lostMinutes;
    }

    /**
     *
     * @param $startDay
     * @param $endDay
     * @return float
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function kValue($startDay, $endDay)
    {
        $whole   = $this->wholeMinutes($startDay, $endDay);
        $working = $this->workingMinutes($startDay, $endDay);
        $kValue  = (int)$whole / (int)$working;
        return round($kValue);
    }

    /**
     * 减排前的时间
     * @return mixed
     */
    public function getBeforeTime()
    {
        $endTimeStr        = time() - 3600 * 24;
        $statTimeStr       = time() - 3600 * 24 * 7;
        $startDay          = date('Y-m-d', $statTimeStr) . ' 00:00:00';   //减排前的开始日期
        $endDay            = date('Y-m-d', $endTimeStr) . ' 23:59:59';    //减排前的结束日期
        $data['start_day'] = $startDay;
        $data['end_day']   = $endDay;
        $data['days']      = 7;
        return $data;
    }

    /**
     * 减排前的k值
     * 说明：如值为1是全部都有效，大于1需要填数
     * @param int $facilityId 设施ID
     * @return float
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function kBeforeValueFacility($facilityId)
    {
        $beforeDayData = $this->getBeforeTime();
        $startDay      = $beforeDayData['start_day'];
        $endDay        = $beforeDayData['end_day'];
        $whole         = $this->wholeMinutes($startDay, $endDay);
        $working       = $this->workingMinutesFacility($startDay, $endDay, $facilityId);
        $result        = (int)$whole / (int)$working;
        return $result;
    }

    /**
     * 减排前的k值
     * 说明：如值为1是全部都有效，大于1需要填数
     * @return float
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function kBeforeValue()
    {
        $beforeDayData = $this->getBeforeTime();
        $startDay      = $beforeDayData['start_day'];
        $endDay        = $beforeDayData['end_day'];
        $whole         = $this->wholeMinutes($startDay, $endDay);
        $working       = $this->workingMinutes($startDay, $endDay);
        $kValue        = (int)$whole / (int)$working;
        $result        = round($kValue, 2);
        return $result;
    }

    // +----------------------------------------------------------------------
    // | 设施
    // +----------------------------------------------------------------------

    /**
     * 通过MongoDb获取数据（设施求和）
     * @param string $table 查询相关表，脱硫：company_industry_monitor_sulfur_minute，脱硝：company_industry_monitor_nitre_minute
     * @param string $startDay 开始日期
     * @param string $endDay 结束日期
     * @param integer $facilityId 设施ID
     * @param string $field 查询的字段，如供浆量是 '$pulp_supply'
     * @param bool $everyDay 是否有每天
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getTheFieldOfSumOfTableOfFacilityId($table, $startDay, $endDay, $facilityId, $field, $everyDay = false)
    {
        //分组
        $groupId  = ['facility_id' => '$facility_id'];
        $groupDay = ['publish_time' => ['$substr' => ['$publish_time', 0, 10]]];
        //是否每天都输出
        if ($everyDay == true) {
            $groupId = array_merge($groupId, $groupDay);
        }
        //条件
        $match = [
            'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,], //开始时间和结束时间
            'facility_id' => (int)$facilityId,
            'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
            'emissions' => ['$ne' => -1],  //排放量不为-1
        ];
        //SQL语句
        $sql = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => $groupId,
                        'field' => [
                            '$sum' => $field
                        ],
                    ]

                ],
            ],
            'cursor' => new \stdClass(),
        ];
        //执行
        $commandEmission = new \MongoDB\Driver\Command($sql);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        //结果
        $data = mongoObjToArray($sulfurDataObj);
        return $data;
    }


    /**
     * 设施脱硫的计算
     * @param $startDay
     * @param $endDay
     * @param $facilityId
     * @param $field
     * @param $everyDay
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getSulfurFieldOfSumOfFacility($startDay, $endDay, $facilityId, $field, $everyDay = false)
    {
        $table  = 'company_industry_monitor_sulfur_minute';
        $result = $this->getTheFieldOfSumOfTableOfFacilityId($table, $startDay, $endDay, $facilityId, $field, $everyDay);
        if (!$result) {
            return false;
        }
        if ($everyDay == false) {
            $result = $result[0]['field'];
        }
        return $result;
    }

    /**
     * 设施脱硝某一字段计算合
     * @param $startDay
     * @param $endDay
     * @param $facilityId
     * @param $field
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getNitreFieldOfSumOfFacility($startDay, $endDay, $facilityId, $field, $everyDay = false)
    {
        $table  = 'company_industry_monitor_nitre_minute';
        $result = $this->getTheFieldOfSumOfTableOfFacilityId($table, $startDay, $endDay, $facilityId, $field, $everyDay);
        if (!$result) {
            return false;
        }
        if ($everyDay == false) {
            $result = $result[0]['field'];
        }
        return $result;
    }

    // +----------------------------------------------------------------------
    // | 排口
    // +----------------------------------------------------------------------

    /**
     * 通过MongoDb获取数据(排口求和)
     * @param string $table 查询相关表，脱硫：company_industry_monitor_sulfur_minute，脱硝：company_industry_monitor_nitre_minute
     * @param string $startDay 开始日期
     * @param string $endDay 结束日期
     * @param integer $drainId 排口ID
     * @param string $field 查询的字段，如供浆量是 '$pulp_supply'
     * @param bool $everyType 是否有每天day,每小时hour
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getTheFieldOfSumOfTableOfDrainId($table, $startDay, $endDay, $drainId, $field, $everyType = false)
    {
        //分组
        $groupId = ['drain_id' => '$drain_id'];
        //是否每天都输出
        if ($everyType == 'day') {
            $groupDay = ['publish_time' => ['$substr' => ['$publish_time', 0, 10]]]; //2019-07-25 10:00:00
            $groupId  = array_merge($groupId, $groupDay);
        }
        //是否每小时都输出
        if ($everyType == 'hour') {
            $groupHour = ['publish_time' => ['$substr' => ['$publish_time', 0, 13]]];
            $groupId   = array_merge($groupId, $groupHour);
        }
        //条件
        $match = [
            'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,], //开始时间和结束时间
            'drain_id' => (int)$drainId,
            'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
            'emissions' => ['$ne' => -1],  //排放量不为-1
        ];
        //SQL语句
        $sql = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => $groupId,
                        'field' => [
                            '$sum' => $field
                        ],
                    ]

                ],
            ],
            'cursor' => new \stdClass(),
        ];
        //执行
        $commandEmission = new \MongoDB\Driver\Command($sql);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        //结果
        $data = mongoObjToArray($sulfurDataObj);
        return $data;
    }

    /**
     * 排口脱硫的计算
     * @param $startDay
     * @param $endDay
     * @param $drainId
     * @param $field
     * @param $every
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getSulfurFieldOfSumOfDrain($startDay, $endDay, $drainId, $field, $every = false)
    {
        $table  = 'company_industry_monitor_sulfur_minute';
        $result = $this->getTheFieldOfSumOfTableOfDrainId($table, $startDay, $endDay, $drainId, $field, $every);
        if ($every == false) {
            $result = $result[0]['field'];
        }
        return $result;
    }

    /**
     * 排口脱硫的计算
     * @param $startDay
     * @param $endDay
     * @param $drainId
     * @param $field
     * @param $every
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getSulfurFieldOfAvgOfDrain($startDay, $endDay, $drainId, $field, $every = false)
    {
        $table  = 'company_industry_monitor_sulfur_minute';
        $result = $this->getTheFieldOfSumOfTableOfDrainId($table, $startDay, $endDay, $drainId, $field, $every);
        if ($every == false) {
            $result = $result[0]['field'];
        }
        return $result;
    }

    /**
     * 排口脱硝某一字段计算合
     * @param $startDay
     * @param $endDay
     * @param $drainId
     * @param $field
     * @param $every
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getNitreFieldOfSumOfDrain($startDay, $endDay, $drainId, $field, $every = false)
    {
        $table  = 'company_industry_monitor_nitre_minute';
        $result = $this->getTheFieldOfSumOfTableOfDrainId($table, $startDay, $endDay, $drainId, $field, $every);
        if ($every == false) {
            $result = $result[0]['field'];
        }
        return $result;
    }

    // +----------------------------------------------------------------------
    // | 公司
    // +----------------------------------------------------------------------
    /**
     * 通过MongoDb获取数据(排口求和)
     * @param string $table 查询相关表，脱硫：company_industry_monitor_sulfur_minute，脱硝：company_industry_monitor_nitre_minute
     * @param string $startDay 开始日期
     * @param string $endDay 结束日期
     * @param integer $companyId 公司ID
     * @param string $field 查询的字段，如供浆量是 '$pulp_supply'
     * @param bool $everyType 是否有每天day,每小时hour
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getTheFieldOfSumOfTableOfCompanyId($table, $startDay, $endDay, $companyId, $field, $everyType = false)
    {
        //分组
        $groupId = ['company_id' => '$company_id'];
        //是否每天都输出
        if ($everyType == 'day') {
            $groupDay = ['publish_time' => ['$substr' => ['$publish_time', 0, 10]]]; //2019-07-25 10:00:00
            $groupId  = array_merge($groupId, $groupDay);
        }
        //是否每小时都输出
        if ($everyType == 'hour') {
            $groupHour = ['publish_time' => ['$substr' => ['$publish_time', 0, 13]]];
            $groupId   = array_merge($groupId, $groupHour);
        }
        //条件
        $match = [
            'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,], //开始时间和结束时间
            'company_id' => (int)$companyId,
            'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
            'emissions' => ['$ne' => -1],  //排放量不为-1
        ];
        //SQL语句
        $sql = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => $groupId,
                        'field' => [
                            '$sum' => $field
                        ],
                    ]

                ],
            ],
            'cursor' => new \stdClass(),
        ];
        //执行
        $commandEmission = new \MongoDB\Driver\Command($sql);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        //结果
        $data = mongoObjToArray($sulfurDataObj);
        return $data;
    }

    /**
     * 公司脱硫的计算
     * @param $startDay
     * @param $endDay
     * @param $companyId
     * @param $field
     * @param $everyDay
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getSulfurFieldOfSumOfCompany($startDay, $endDay, $companyId, $field, $everyDay = false)
    {
        $table  = 'company_industry_monitor_sulfur_minute';
        $result = $this->getTheFieldOfSumOfTableOfCompanyId($table, $startDay, $endDay, $companyId, $field, $everyDay);
        if ($everyDay == false) {
            $result = $result[0]['field'];
        }
        return $result;
    }

    /**
     * 公司脱硝某一字段计算合
     * @param $startDay
     * @param $endDay
     * @param $drainId
     * @param $field
     * @param $everyDay
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getNitreFieldOfSumOfCompany($startDay, $endDay, $companyId, $field, $everyDay = false)
    {
        $table  = 'company_industry_monitor_nitre_minute';
        $result = $this->getTheFieldOfSumOfTableOfCompanyId($table, $startDay, $endDay, $companyId, $field, $everyDay);
        if ($everyDay == false) {
            $result = $result[0]['field'];
        }
        return $result;
    }


    // +----------------------------------------------------------------------
    // | 行业
    // +----------------------------------------------------------------------
    /**
     * 通过MongoDb获取数据(排口求和)
     * @param string $table 查询相关表，脱硫：company_industry_monitor_sulfur_minute，脱硝：company_industry_monitor_nitre_minute
     * @param string $startDay 开始日期
     * @param string $endDay 结束日期
     * @param integer $industryId 行业ID
     * @param string $field 查询的字段，如供浆量是 '$pulp_supply'
     * @param bool $everyType 是否有每天day,每小时hour
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getTheFieldOfSumOfTableOfIndustryId($table, $startDay, $endDay, $industryId, $field, $everyType = false)
    {
        //分组
        $groupId = ['industry_id' => '$industry_id'];
        //是否每天都输出
        if ($everyType == 'day') {
            $groupDay = ['publish_time' => ['$substr' => ['$publish_time', 0, 10]]]; //2019-07-25 10:00:00
            $groupId  = array_merge($groupId, $groupDay);
        }
        //是否每小时都输出
        if ($everyType == 'hour') {
            $groupHour = ['publish_time' => ['$substr' => ['$publish_time', 0, 13]]];
            $groupId   = array_merge($groupId, $groupHour);
        }
        //条件
        $match = [
            'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,], //开始时间和结束时间
            'industry_id' => (int)$industryId,
            'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
            'emissions' => ['$ne' => -1],  //排放量不为-1
        ];
        //SQL语句
        $sql = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => $group = [
                        '_id' => $groupId,
                        'field' => [
                            '$sum' => $field
                        ],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        //执行
        $commandEmission = new \MongoDB\Driver\Command($sql);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        //结果
        $data = mongoObjToArray($sulfurDataObj);
        return $data;
    }

    /**
     * 获取每一个行业的数据
     * @param $table
     * @param $startDay
     * @param $endDay
     * @param $field
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-29
     */
    public function getTheFieldOfSumOfTableOfEveryIndustryId($table, $startDay, $endDay, $field)
    {
        //分组
        $groupId = ['industry_id' => '$industry_id'];
        //条件
        $match = [
            'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,], //开始时间和结束时间
            'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
            'emissions' => ['$ne' => -1],  //排放量不为-1
        ];
        //SQL语句
        $sql = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => $group = [
                        '_id' => $groupId,
                        'field' => [
                            '$sum' => $field
                        ],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        //执行
        $commandEmission = new \MongoDB\Driver\Command($sql);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        //结果
        $data = mongoObjToArray($sulfurDataObj);
        return $data;
    }

    /**
     * 行业脱硫的计算
     * @param $startDay
     * @param $endDay
     * @param $industryId
     * @param $field
     * @param $everyDay
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getSulfurFieldOfSumOfIndustry($startDay, $endDay, $industryId, $field, $everyDay = false)
    {
        $table  = 'company_industry_monitor_sulfur_minute';
        $result = $this->getTheFieldOfSumOfTableOfIndustryId($table, $startDay, $endDay, $industryId, $field, $everyDay);
        if (!$result) {
            return false;
        }
        if ($everyDay == false) {
            $result = $result[0]['field'];
        }
        return $result;
    }

    /**
     * 获取每一个行业的值
     * @param $startDay
     * @param $endDay
     * @param $field
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-29
     */
    public function getSulfurFieldOfSumOfEveryIndustry($startDay, $endDay, $field)
    {
        $table    = 'company_industry_monitor_sulfur_minute';
        $result   = $this->getTheFieldOfSumOfTableOfEveryIndustryId($table, $startDay, $endDay, $field);
        $result   = mongoObjToArray($result);
        $newArray = [];
        foreach ($result as $k => $v) {
            $newArray[$k]['industry_id']   = $v['_id']->industry_id;
            $newArray[$k]['so2_emissions'] = $v['field'];
        }
        return $newArray;
    }

    /**
     * 行业脱硝某一字段计算合
     * @param $startDay
     * @param $endDay
     * @param $industryId
     * @param $field
     * @param $everyDay
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getNitreFieldOfSumOfIndustry($startDay, $endDay, $industryId, $field, $everyDay = false)
    {
        $table  = 'company_industry_monitor_nitre_minute';
        $result = $this->getTheFieldOfSumOfTableOfIndustryId($table, $startDay, $endDay, $industryId, $field, $everyDay);
        if ($everyDay == false) {
            $result = $result[0]['field'];
        }
        return $result;
    }

    /**
     * 获取每一个行业的值
     * @param $startDay
     * @param $endDay
     * @param $field
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-29
     */
    public function getNitreFieldOfSumOfEveryIndustry($startDay, $endDay, $field)
    {
        $table    = 'company_industry_monitor_nitre_minute';
        $result   = $this->getTheFieldOfSumOfTableOfEveryIndustryId($table, $startDay, $endDay, $field);
        $result   = mongoObjToArray($result);
        $newArray = [];
        foreach ($result as $k => $v) {
            $newArray[$k]['industry_id']   = $v['_id']->industry_id;
            $newArray[$k]['no2_emissions'] = $v['field'];
        }
        return $newArray;
    }

    // +----------------------------------------------------------------------
    // | （三）总方法的封装，求总数量
    // +----------------------------------------------------------------------
    /**
     * 通过MongoDb获取数据
     * @param string $table 查询相关表，脱硫：company_industry_monitor_sulfur_minute，脱硝：company_industry_monitor_nitre_minute
     * @param string $startDay 开始日期
     * @param string $endDay 结束日期
     * @param integer $facilityId 设施ID
     * @param string $field 查询的字段，如循环泵是 'circulating_pump1_witching_stateX'
     * @param string $value 查询的字段的值，如循环泵的值是1
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getTheFieldOfCountOfTable($table, $startDay, $endDay, $facilityId, $field, $value)
    {
        //分组
        $groupId = ['facility_id' => '$facility_id'];
        //条件
        $match = [
            'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,], //开始时间和结束时间
            'facility_id' => (int)$facilityId,
            $field => $value,  //例如：循环泵1的字段是：即$field = circulating_pump1_witching_stateX, $value = 1，
            'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
            'emissions' => ['$ne' => -1],  //排放量不为-1
        ];
        //SQL语句
        $sql = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => null,
                        'count' => [
                            '$sum' => 1
                        ],
                    ]

                ],
            ],
            'cursor' => new \stdClass(),
        ];
        //执行
        $commandEmission = new \MongoDB\Driver\Command($sql);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        //结果
        $data = mongoObjToArray($sulfurDataObj);
        return $data;
    }

    /**
     * 脱硫的计算
     * @param $startDay
     * @param $endDay
     * @param $facilityId
     * @param $field
     * @param $value
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getSulfurFieldOfCount($startDay, $endDay, $facilityId, $field, $value)
    {
        $table  = 'company_industry_monitor_sulfur_minute';
        $result = $this->getTheFieldOfCountOfTable($table, $startDay, $endDay, $facilityId, $field, $value);
        if (empty($result)) {
            $data = 0;
        } else {
            $data = $result[0]['count'];
        }
        return $data;
    }

    /**
     * 脱硝某一字段计算合
     * @param $startDay
     * @param $endDay
     * @param $facilityId
     * @param $field
     * @param $value
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-22
     */
    public function getNitreFieldOfCount($startDay, $endDay, $facilityId, $field, $value)
    {
        $table  = 'company_industry_monitor_nitre_minute';
        $result = $this->getTheFieldOfCountOfTable($table, $startDay, $endDay, $facilityId, $field, $value);
        if (empty($result)) {
            $data = 0;
        } else {
            $data = $result[0]['count'];
        }
        return $data;
    }

    /**
     * 通过MongoDb获取数据
     * @param string $startDay 开始日期
     * @param string $endDay 结束日期
     * @param string $table 查询的表
     * @param integer $denominator 分母
     * @param bool $drain 是否有排口
     * @param bool $companyId 是否有排口公司ID
     * @param bool $everyDay 是否每天都要输出
     * @param bool $industryId 是否有行业ID
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei
     */
    public function getSulfurDataByMongoSql($startDay, $endDay, $table, $denominator, $drain = true, $companyId = false, $everyDay = false, $industryId = false)
    {
        //step1:是否有排口
        $groupId       = ['drain_name' => '$drain_name', 'company_id' => '$company_id', 'company_name' => '$company_name'];
        $groupDrain    = ['drain_id' => '$drain_id'];
        $groupDay      = ['publish_time' => ['$substr' => ['$publish_time', 0, 10]]];
        $groupIndustry = ['industry_id' => '$industry_id'];
        //是否输出排口
        if ($drain) {
            $groupId = array_merge($groupId, $groupDrain);
        }
        //是否每天都输出
        if ($everyDay) {
            $groupId = array_merge($groupId, $groupDay);
        }
        //是否有行业
        if ($industryId && $everyDay == false) {
            $groupId = $groupIndustry;
        }
        //是否有行业和日期
        if ($industryId && $everyDay == true) {
            $groupId = array_merge($groupIndustry, $groupDay);
        }

        //step2:是否有公司
        $match          = [
            'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,],
            'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
            'emissions' => ['$ne' => -1],  //排放量不为-1
        ];
        $matchCompanyId = [
            'company_id' => (int)$companyId
        ];
        if ($companyId) {
            $match = array_merge($match, $matchCompanyId);
        }

        //step2:查询
        $sqlEmission     = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => $groupId,
                        'so2_emissions' => ['$sum' => [
                            '$divide' => ['$emissions', $denominator]
                        ]],
                        'tsp_emissions' => [
                            '$sum' => [
                                '$divide' => [
                                    ['$multiply' => ['$export_smoke_dust', '$inlet_gas_volume']], $denominator //TSP的排放量/单位
                                ]
                            ]
                        ],
                    ]

                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        //step3:结果
        $data = mongoObjToArray($sulfurDataObj);
        return $data;
    }

    /**
     * 通过MongoDb获取数据
     * @param string $startDay 开始日期
     * @param string $endDay 结束日期
     * @param string $table 查询的表
     * @param integer $denominator 分母
     * @param bool $drain 是否有排口
     * @param bool $companyId 是否有排口公司ID
     * @param bool $everyDay 是否每天都输出
     * @param bool $industryId 是否有行业ID
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei
     */
    public function getNitreDataByMongoSql($startDay, $endDay, $table, $denominator, $drain = true, $companyId = false, $everyDay = false, $industryId = false)
    {
        //step1:是否有排口
        $groupId       = ['drain_name' => '$drain_name', 'company_id' => '$company_id', 'company_name' => '$company_name'];
        $groupDrain    = ['drain_id' => '$drain_id'];
        $groupDay      = ['publish_time' => ['$substr' => ['$publish_time', 0, 10]]];
        $groupIndustry = ['industry_id' => '$industry_id'];
        //是否输出排口
        if ($drain) {
            $groupId = array_merge($groupId, $groupDrain);
        }
        //是否每天都输出
        if ($everyDay == true) {
            $groupId = array_merge($groupId, $groupDay);
        }
        //是否有行业
        if ($industryId && $everyDay == false) {
            $groupId = $groupIndustry;
        }
        //是否有行业和日期
        if ($industryId && $everyDay == true) {
            $groupId = array_merge($groupIndustry, $groupDay);
        }
        //step2:是否有公司
        $match          = [
            'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,],
            'emission' => ['$ne' => NAN],  //排放量不为NaN
        ];
        $matchCompanyId = [
            'company_id' => (int)$companyId
        ];
        if ($companyId) {
            $match = array_merge($match, $matchCompanyId);
        }

        //step2:查询
        $sqlEmission     = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => $match
                ],
                [
                    '$group' => [
                        '_id' => $groupId,
                        'nox_emissions' => ['$sum' => [
                            '$divide' => ['$emission', $denominator]
                        ]],
                    ]

                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
        $sulfurDataObj   = $this->mongodb->executeCommand('huanxin', $commandEmission);
        //step3:结果
        $data = mongoObjToArray($sulfurDataObj);
        return $data;
    }

    /**
     * 丢失小时数
     * @param $startDay
     * @param $endDay
     * @param $table
     * @param $wholeHours
     * @return bool|int
     * @throws \MongoDB\Driver\Exception\Exception
     * @author hongwei 2019-07-04
     */
    public function lostHours($startDay, $endDay, $table, $wholeHours)
    {
        //step2:工作的小时
        $sqlWorkingHoursSql     = [
            'aggregate' => $table,
            'pipeline' => [
                [
                    '$match' => [
                        'publish_time' => ['$gte' => $startDay, '$lte' => $endDay,],
                        'export_smoke_dust' => ['$ne' => -1],  //烟尘不为-1
                        'emissions' => ['$ne' => -1],  //排放量不为-1
                    ]
                ],
                [
                    '$group' => [
                        '_id' => null,
                        'count' => ['$sum' => 1],
                    ]
                ],
            ],
            'cursor' => new \stdClass(),
        ];
        $commandWorkingHoursObj = new \MongoDB\Driver\Command($sqlWorkingHoursSql);
        $workingHoursObj        = $this->mongodb->executeCommand('huanxin', $commandWorkingHoursObj);
        $workingHours           = mongoObjToArray($workingHoursObj);
        $workingHours           = round($workingHours[0]['count'] / 2 / 60); //四舍五入，2个设施

        //step3:丢失小时
        $lostHours = (int)$wholeHours - (int)$workingHours; //丢失小时数
        if ($lostHours <= 0) {
            return false;
        }

        //step4:
        return $lostHours;
    }

}